// 导入React Hooks
import { useEffect, useState } from "react";

// 导入antd组件
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";

// 导入获取文章频道列表方法
import GetChannelList from "../../hooks/useGetChannel";

// 导入样式
import "./index.scss";

// 导入路由模块
import { Link, useSearchParams } from "react-router";

// 导入富文本编辑器包
import ReactQuill from "react-quill-new";
import "react-quill-new/dist/quill.snow.css";

// 导入网络请求APi
import {
  addArticleAPI,
  reGetArticleListAPI,
  putArticleAPI,
} from "../../apis/article";

// 导入声明文件
import type { ArticleSubmitType } from "../../types/article";
import type { UploadFile, UploadProps, RadioChangeEvent } from "antd";

const { Option } = Select;

const Publish = () => {
  // 获取文章频道列表
  const { channelList } = GetChannelList();

  // 提交表单方法
  const onFinish = (values: ArticleSubmitType) => {
    if (imagesList.length != imgType) {
      return message.error("请上传" + imgType + "张图片");
    }

    // 收集表单数据集
    const submitData = {
      title: values.title,
      content: values.content,
      cover: {
        type: imgType,
        images: imagesList.map((item) => {
          if (item.response) {
            return item.response.data.url;
          } else {
            return item.url;
          }
        }),
      },
      channel_id: values.channel_id,
    };
    if (ArticleId) {
      // 编辑表单
      putArticleAPI(ArticleId, submitData);
    } else {
      // 提交表单
      addArticleAPI(submitData);
    }
  };

  // 上传图片方法
  const [imagesList, setImagesList] = useState<UploadFile[]>([]);
  const OnUpLoad: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    setImagesList(newFileList);
  };

  // 封面类型切换
  const [imgType, setImgType] = useState(0);
  const OnTypeChange = (values: RadioChangeEvent) => {
    setImgType(values.target.value);
  };

  // 编辑进入文章详情页
  const [searchParams] = useSearchParams();
  // 获取路由参数
  const ArticleId = searchParams.get("id") as string;
  const [form] = Form.useForm();
  useEffect(() => {
    const reGetArticle = async () => {
      // 获取id中的数据
      const res = await reGetArticleListAPI(ArticleId);
      // 回填表单
      form.setFieldsValue({ ...res.data.data, type: res.data.data.cover.type });
      // 图片类型
      setImgType(res.data.data.cover.type);
      // 回填图片
      setImagesList(
        res.data.data.cover.images.map((url: string) => {
          return { url };
        })
      );
    };
    // 判断有id才能执行回填操作
    if (ArticleId) {
      reGetArticle();
    }
  }, [ArticleId, form]);
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={"/"}>首页</Link> },
              { title: `${ArticleId ? "编辑" : "发布"}文章` },
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择文章频道" }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelList.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={OnTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgType > 0 && (
              <Upload
                listType="picture-card"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                name="image"
                onChange={OnUpLoad}
                maxCount={imgType}
                fileList={imagesList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <ReactQuill
              theme="snow"
              className="publish-quill"
              placeholder="请输入文章内容"
            />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
